'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: github_oauth.py
* @Time: 2025/11/18
* @All Rights Reserve By Brtc
'''
import urllib
from  urllib import parse

import requests

from .oauth import OAuth, OAuthUserInfo


class GithubOAuth(OAuth):
    """Github 第三方授权认证"""
    _AUTHORIZE_URL = "https://github.com/login/oauth/authorize" # 跳转授权接口
    _ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token" # 获取令牌接口
    _USER_INFO_URL = "https://api.github.com/user" # 获取用户信息
    _EMAIL_INFO_URL = "https://api.github.com/user/emails" # 获取用户邮箱

    def get_provider(self) -> str:
        return "github"

    def get_authorization_url(self) -> str:
        params = {
            "client_id": self.client_id,
            "redirect_uri": self.redirect_uri,
            "scope": "user:email",
        }
        return f"{self._AUTHORIZE_URL}?{urllib.parse.urlencode(params)}"


    def get_access_token(self, code: str) -> str:
        #1、组装请求数据
        data = {
            "client_id": self.client_id,
            "client_secret": self.client_secret,
            "code" :code,
            "redirect_uri": self.redirect_uri,
        }
        headers = {"Accept": "application/json"}

        #2、发起  post请求
        resp = requests.post(self._ACCESS_TOKEN_URL, data=data, headers=headers)
        resp.raise_for_status()
        resp_json = resp.json()
        #3、提取access_token
        access_token = resp_json.get("access_token")
        if not access_token:
            raise ValueError(f"Github OAuth授权失败:{resp_json}")
        return access_token


    def get_raw_user_info(self, token:str) ->dict:
        #1、组装请求数据
        headers = {"Authorization": f"token {token}"}
        #2、发起 get 请求获取用户数据
        resp = requests.get(self._USER_INFO_URL, headers=headers)
        resp.raise_for_status()
        raw_info = resp.json()
        #3、发起 get 请求获取用户邮箱
        email_resp = requests.get(self._EMAIL_INFO_URL, headers=headers)
        email_resp.raise_for_status()
        email_info = email_resp.json()
        #4、提取邮箱数据
        primary_email = next((email for email in email_info if email.get("primary", None)), None)
        return {**raw_info, "email":primary_email.get("email", None)}


    def _transform_user_info(self, raw_info:dict) ->OAuthUserInfo:
        #1、提取邮箱信息，如果不逊在则设置一个默认邮箱
        email = raw_info.get("email")
        if not email:
            email = f"{raw_info.get('id')}+{raw_info.get('login')}@user.no-replay@brtc-github.com"
        #2、组装数据
        return OAuthUserInfo(
            id = str(raw_info.get("id")),
            name = str(raw_info.get("name")),
            email = str(email),
        )










